"""用于 LangGraph 的天气工具。

本模块提供了一个简单的天气查询工具，可与 LangGraph 一起使用
来获取指定位置的天气信息。
"""
import json
import random
from datetime import datetime

from copilotkit.langgraph import copilotkit_emit_state
from pydantic import BaseModel, Field
from langchain_core.tools import Tool

from app.core.logging import logger


class WeatherQuery(BaseModel):
    location: str = Field(..., description="包含位置信息的查询字符串")


def get_weather(location: str) -> str:
    """
    获取指定位置的天气信息。

    Args:
        query (str): 包含位置信息的查询字符串

    Returns:
        str: 格式化的天气信息
    """
    # 这里可以集成真实的天气API
    # 为了演示目的，我们返回模拟数据






    # 模拟天气数据
    weather_conditions = ["晴朗", "多云", "阴天", "小雨", "大雨", "雷阵雨", "小雪", "大雪"]
    temp = round(random.uniform(5, 35), 1)
    humidity = random.randint(30, 95)
    wind_speed = round(random.uniform(0, 10), 1)
    wind_direction = random.choice(["东", "南", "西", "北", "东北", "西北", "东南", "西南"])
    # 获取当前日期和时间
    now = datetime.now()
    formatted_date = now.strftime("%Y-%m-%d %H:%M")
    # 构建JSON格式的天气数据
    weather_data = {
        "location": location,
        "condition": random.choice(weather_conditions),
        "temperature": temp,
        "humidity": humidity,
        "wind": {
            "speed": wind_speed,
            "direction": wind_direction
        },
        "updated_at": formatted_date
    }

    result = json.dumps(weather_data, ensure_ascii=False)
    logger.info(f"天气查询结果: {result[:100]}...")



    # return f"{location}的天气情况:\n温度: {weather_data['temperature']}\n天气状况: {weather_data['condition']}\n湿度: {weather_data['humidity']}\n风速: {weather_data['wind_speed']}"
    return result


# 创建天气工具实例
weather_tool = Tool(
    name="get_weather",
    description="获取指定位置的天气信息。输入参数应该是位置名称。",
    func=get_weather,
    args_schema=WeatherQuery,
    handle_tool_error=True
)
